const { User, UserPermissionMapping, Permission, Resource, PermissionResourceMapping, Childmenu } = require('../../database/index');
const { getExecutedSql } = require('../../logger');

module.exports = async (req, res) =>
{
    const account = req.account.account; // 从请求中获取用户的账号信息
    // 根据账号信息查询对应的 uid
    const user = await User.findOne({
        where: { account: account },
    });
    if (user) {
        const uid = user.uid;
        // 根据 uid 获取相应的权限
        const userPermissions = await UserPermissionMapping.findAll({
            where: { uid },
            include: [{ model: Permission, attributes: ['permission_id', 'permission_name', 'description'] }]
        });

        // // 获取权限 ID 列表
        const permissionIds = userPermissions.map((userPermission) => userPermission.permission_id);

        // // 根据权限 ID 获取资源-权限映射关系
        const resourcePermissionMappings = await PermissionResourceMapping.findAll({
            where: { permission_id: permissionIds },
            attributes: ['resource_id', 'permission_id']
        });
        // // 获取资源 ID 列表
        const resourceIds = resourcePermissionMappings.map((mapping) => mapping.resource_id);
        // // 根据资源 ID 获取资源文件
        const resources = await Resource.findAll({
            where: { resource_id: resourceIds },
            attributes: ['resource_id', 'resource_name', 'description', 'path', 'child_menu', 'icon'],
            include: [
                {
                    model: Childmenu, // 关联子菜单模型
                    attributes: ['child_name', 'child_path', 'child_icon', 'component'] // 子菜单模型的字段列表
                }
            ]
        });


        const executedSql = getExecutedSql()

        // 进一步处理获取的资源文件和权限等信息
        res.status(200).send({
            data: resources,
            meta: {
                msg: "获取成功",
                status: 200
            },
            sql: executedSql
        })
    } else {
        res.status(404).send('User not found');
    }
};
